// pages/select/select.js
const db= wx.cloud.database();
const chooseLocation = requirePlugin('chooseLocation');
const key = 'H54BZ-5MS6X-3ID4E-T6W5U-XTW5V-HRBNF'; //使用在腾讯位置服务申请的key
const referer = 'Agriculture'; //调用插件的app的名称

const category = '乡村,城镇';
var app=getApp();
 var y=app.globalData.y;

Page({

  /**
   * 页面的初始数据
   */
  data: {
        user:{},
        onSelect:"",
        radio:'1',
        land:{
            user:{},    //发布者
            img:[],         //图片
            location:{},    //地理位置
            type:"",        //土地流转类型
            label:"",       //土地性质
            area:"",        //面积
            detail:"",      //详情
            VR:"",
        },
        tool:{
            user:{},
            img:[],         //图片
            location:{},    //地理位置
            type:"",        //工具转让方式
            name:"",       //工具名称
            price:"",        //价格
            detail:"",      //详情
        },
        fileList1: [],
        fileList2:[],
        tabs: ['发布土地', '发布农具'],
        current:0,
        show: false,
        actions: [],
        description:'',
        selected:'元',
        selshow:false,
        selicon:'arrow-down',
        selectList:['元/时','元/天','元/月','元'],
        VR:[],
        preList:[],
        delete:0
  },

    //选取图片
    afterRead1(event) {
        const { file } = event.detail;

        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        var oldList = this.data.fileList1;
        var newList = oldList.concat(file);
        this.setData({
            fileList1:newList
        })
    },
    afterRead2(event) {
        const { file } = event.detail;
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        var oldList = this.data.fileList2;
        var newList = oldList.concat(file);
        this.setData({
            fileList2:newList
        })
    },
    afterReadVR(event) {
        const { file } = event.detail;

        this.setData({
            VR:file
        })
    },
    //删除图片
    delete1(event){

            var that = this;
            var index = event.detail.index
            var newList = that.data.fileList1
            newList.splice(index,1)
            that.setData({
                fileList1:newList
            })
    },
    delete2(event){
                var that = this;
                var index = event.detail.index
                var newList = that.data.fileList2
                newList.splice(index,1)
                that.setData({
                    fileList2:newList
                })
    },
    async deleteVR(event){
        this.setData({
            VR:[]
        })
        let{preList} = this.data;
        if(preList.length != 0){
            await this.removeVR(preList) 
        }
    },

    // 专门用来展示倒计时以及页面跳转的方法
    delayTime() {
                // 1.每次点击结算,都需要将倒计时秒数还原
                var time = 3
                // 2.展示倒计时弹框
                this.showTips(time)
                // 3.使用setInterval 实现倒计时
                var timeId = setInterval(() => {
                        // 3.1 秒数每次减1
                    time -= 1
                        // 3.3 做一个判断,如果秒数为0的话清除定时器
                    if(time <= 0) {
                            clearInterval(timeId)
                            // 3.4 进行页面跳转
                            wx.switchTab({
                                url:'/pages/index/index'
                            })
                            return
                    }
                    // 3.2  定时器每循环一次调一次弹窗
                    this.showTips(time)
                },1000)
    },  
    // 弹窗方法 
    showTips(n) {
                // 调用 uni.showToast() 方法，展示提示消息
                wx.showToast({
                    duration:1500,  // 1.5 秒后自动消失
                    mask:true,   // 为页面添加透明遮罩，防止点击穿透
                    title:'OK! 即将跳转 ' + n,
                })
        
    },

    //将土地图片在云存储的路劲渲染到 land 对象
    async uploadLand(){
        var that = this
        var imgList = await that.uploadFileList(that.data.fileList1);
        that.setData({
            ['land.user']:that.data.user,
            ['land.img']:imgList,
        })
    },
    //将农具图片在云存储的路劲渲染到 tool 对象
    async uploadTool(){
        var that = this
        var imgList = await that.uploadFileList(that.data.fileList2);
        that.setData({
            ['tool.user']:that.data.user,
            ['tool.img']:imgList,
        })
    },
    //上传图片到云存储，并返回访问地址
    async uploadFileList(pathList){

        var that = this
        wx.showLoading({
            title: '图片上传中.....',
        });
        var fileIdList = [];

        for (let i = 0; i < pathList.length; i++) {
            let fileId = await that.uploadList(pathList[i].url);
            fileIdList.push(fileId);
        }
        wx.showToast({
            title: '图片上传完成！',
        })
        return fileIdList;
    },     
    async uploadList(imgPath){
        var that = this;
        var id;
        await  wx.cloud.uploadFile({
            cloudPath: that.data.user._id +'/'+ Date.now()+'.png',
            filePath: imgPath // 文件路径
        }).then(res => {
            // get resource ID
            id=res.fileID
        }).catch(error => {
            // handle error
        })
        return id;
    },

    //上传全景图
    async uploadVR(imgPath,landid,pre){
        var user = wx.getStorageSync('userFlag').user
        var cloudPath="";  
        if(!pre){
           cloudPath  = user._id +'/'+landid+new Date().getTime()+'VR.png';
        }else{
            cloudPath = user._id+'/'+new Date().getTime()+'previewVR.png';
        }
        var id;
        await wx.cloud.uploadFile({
            cloudPath:cloudPath ,
            filePath: imgPath // 文件路径
        }).then(res => {
            id=res.fileID
        }).catch(error => {
        })
        return id;
    },

    //检验并上传土地
    submit(e){
        var c=true;
        var that = this;
        const x=this.selectComponent('#set-label')
        if(x.data.error||x.value=='')
        {
            x.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        const y=this.selectComponent('#set-type')
        if(y.data.error||y.value=='')
        {
            y.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        const z=this.selectComponent('#set-area')
        if(z.data.error||z.value=='')
        {
            z.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        const v=this.selectComponent('#set-location')
        if(v.data.error||v.value=='')
        {
            v.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        const   m=this.selectComponent('#set-detail')
        if(m.data.error||m.value=='')
        {
            m.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        if(!c)
        {
        wx.showModal({
            title: '提示',
            content: '输入错误',
            showCancel:false,
            success (res) {
            }
            })
        }
        else
        {if(this.data.fileList1.length==0)
        {
            wx.showToast({
                title: '未上传图片',
                icon:'error',
                showCancel:false,
            })
            return
        }
        wx.showModal({
            title: '提示',
            content: '确认提交',
            async  success (res) {
                var landid;
                if (res.confirm) {
                    await that.uploadLand()
                    var area = e.detail.value.area;
                    var detail = e.detail.value.detail;
                    that.setData({
                        ['land.area']:area,
                        ['land.detail']:detail,
                    })
                    var land=that.data.land;
                   await wx.cloud.callFunction({
                        name: 'addLand',
                        data:{
                            land:land
                        }
                    }).then(res => {
                         landid = res.result._id
                            that.setData({
                                land:{},
                                fileList1:[]
                                
                            })
                            
                        }).catch(console.error)

                    var {VR} = that.data;
                    var {preList} = that.data;
                    if(VR[0]){ 
                            wx.showLoading({
                                title: '正在上传全景图',
                              })
                              if(preList.length != 0){
                                  await that.removeVR(preList);
                                  that.setData({})
                              }
                            var vr = await that.uploadVR(VR[0].url,landid,false);
                            await db.collection('land').doc(landid).update({
                                data:{
                                    VR:vr
                                }
                            }).then(res=>{
                            })
                    }else{

                    }
                     
                    wx.showToast({
                        duration:2000,  // 1.5 秒后自动消失
                        mask:true,   // 为页面添加透明遮罩，防止点击穿透
                        title:'土地上传完成',
                    })
                       that.delayTime();
                } 
            }
        })

        }
    },

    //检验并上传农具
    submit2(e)
    {
        var c=true;
        const x=this.selectComponent('#set-toolname')
        if(x.data.error||x.value=='')
        {
            x.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        const y=this.selectComponent('#set-tooltype')
        if(y.data.error||y.value=='')
        {
            y.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        const z=this.selectComponent('#set-price')
        if(z.data.error||z.value=='')
        {
            z.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        const v=this.selectComponent('#set-tooldetail')
        if(v.data.error||v.value=='')
        {
            v.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }
        const  n=this.selectComponent('#set-tooladdress')
        if(n.data.error||n.value=='')
        {
            n.setData({
                errorMessage:"输入错误"
            })
            c=false;
        }

        if(!c)
        {
        wx.showModal({
            title: '提示',
            content: '输入错误',
            showCancel:false,
            success (res) {
            }
            })
        }
        else
        {
            if(this.data.fileList2.length==0)
        {
        wx.showToast({
            title: '未上传图片',
            icon:'error',
        })
        return
        }
        var that = this; 
        wx.showModal({
            title: '提示',
            content: '确认提交',
            async success (res) {
            if (res.confirm) {

                await that.uploadTool();
                var name = e.detail.value.name;
                var price = e.detail.value.price;
                var detail = e.detail.value.detail;

                that.setData({
                    ['tool.name']:name,
                    ['tool.price']:price+that.data.selected,
                    ['tool.detail']:detail,
                })

                var tool=that.data.tool;

                wx.cloud.callFunction({
                        name: 'addTool',
                        data:{
                            tool:tool
                        }
                    }).then(res => {
                        that.setData({
                            tool:{},
                            fileList2:[]
                        })
                    }).catch(console.error)

                    wx.showToast({
                        duration:2000,  // 1.5 秒后自动消失
                        mask:true,   // 为页面添加透明遮罩，防止点击穿透
                        title:'农具上传完成',
                    })

                    that.delayTime();
            } 
            }
            })
        }  
    },
    onHide:async function(){
        let{preList} = this.data;
        let delte = this.data.delete;
        if(delte===0){
            if(preList.length != 0){
                await this.removeVR(preList) 
            } 
        }
    },

    //地图选点
    chooseLocation(){
        wx.navigateTo({
        url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer +'&category=' + category
        });
    },

    //生命周期函数--监听页面显示
    onShow: function () {
        var that = this;
        var flag = wx.getStorageSync('userFlag').flag; 
            if(flag==0) {
                wx.showModal({
                    title: '提示',
                    content: '你还未完善个人信息，是否立刻去完善？',
                    success (res) {
                        if (res.confirm) {
                            wx.switchTab({
                                url: '/pages/user/index',
                            })
                        } else if (res.cancel) {
                                    wx.switchTab({
                                        url: '/pages/index/index',
                                    })
                                }
                        }
                })
            }

            const location = chooseLocation.getLocation();
            var x={};
        
            var cur = that.data.current;
        
                if (cur == 0) {
                x = this.selectComponent('#set-location');
                    that.setData({
                        ['land.location']:location,
                    })
                }else{
                    x = this.selectComponent('#set-tooladdress');
                    that.setData({
                        ['tool.location']:location
                    })
                } 
                
                if(location!=null)
                {
                    x.setData({
                        error:false,
                        errorMessage:''
                    })
                }

                if(y>0)
                {
                    wx.showTabBarRedDot({
                      index: 2,
                    })
                }
                else{
                    wx.hideTabBarRedDot({
                      index: 2,
                    })
                }

                that.setData({
                    delete:0
                })
    },
    onLoad:function(){
        var user = wx.getStorageSync('userFlag').user;
        this.setData({
            delete:0,
            user:user
        })
    },

        //获取网络路径
        async path(fileid){
            var path="";
            await wx.cloud.getTempFileURL({
                fileList: [{
                    fileID: fileid,
                    maxAge: 60 * 10, 
                  }]
            }).then(res=>{
                path = res.fileList[0].tempFileURL;
            })
            return path;
        },
    
        //预览
        async preview(){
            var {preList} = this.data;
            var that = this;
            var {VR} = this.data;
                if(VR[0]){ 
                    wx.showLoading({
                        title: '加载中',
                    })
                    //如果还存在测试图片，则删除；
                    if(preList.length != 0){
                        await that.removeVR(preList);
                        that.setData({
                            preList:[]
                        })
                        preList=[];
                    }
                    var fileid = await this.uploadVR(VR[0].url,"",true);
                    preList.push(fileid);
                    
                    that.setData({
        
                        preList:preList
                    })
                    wx.hideLoading({
                        success: (res) => {},
                    })
                    var path = await that.path(fileid);
                    that.setData({
                        delete:1
                    })
                    wx.navigateTo({
                        url: '/pages/vr/vr?id='+path
                    })
                }else{
                    wx.showToast({
                    title: '你还未选择图片',
                    icon:"none"
                    })
                }
            },
    
        async removeVR(VR){
            await  wx.cloud.deleteFile({
                fileList: VR
              }).then(res => {
              }).catch(error => {
              })
        },

    onClose() {
        this.setData({ show: false });
    },
    onSelect1(event) {
        var label = event.detail.name;
        this.setData({
            ['land.label']: label
        })
        const   m=this.selectComponent('#set-label')
        m.setData({
            error:false,
            errorMessage:''
        })
    },
    onSelect2(event) {
        var type = event.detail.name;
        this.setData({
        ['land.type']: type
        })
        const   m=this.selectComponent('#set-type')
            m.setData({
                error:false,
                errorMessage:''
            })
    },
    onSelect3(event) {
        var type = event.detail.name;
        this.setData({
        ['tool.type']: type
        })
        const   m=this.selectComponent('#set-tooltype')
        m.setData({
            error:false,
            errorMessage:''
        })
    },
    onSelect4(event){
        var type = event.detail.name;
        this.setData({
        ['tool.name']: type
        })
        const   m=this.selectComponent('#set-toolname')
        m.setData({
            error:false,
            errorMessage:''
        })
    },
    selectLabel(){
        this.setData({ 
            onSelect:"onSelect1",
            show: true,
            description:"您的土地是什么类型的?",
            actions:[
                { name: '耕地' },
                { name: '林地' },
                { name: '园地' },
                { name: '草地' },
                { name: '养殖' },
            ]
        });
    },
    selectType(){
        this.setData({ 
            onSelect:"onSelect2",
            show: true,
            description:"您希望以何种方式流转?",
            actions:[
                { name: '转包' },
                { name: '出租' },
                { name: '互换' },
                { name: '抵押' },
            ]
        });
    },
    selectNameF(){
        this.setData({ 
            onSelect:"onSelect4",
            show: true,
            description:"选择农具名称",
            actions:[
                { name: '镰刀' },
                { name: '锄头' },
                { name:'其他'},
            ]
        });
    },
    selectTypeF(){
        this.setData({ 
            onSelect:"onSelect3",
            show: true,
            description:"您希望以何种方式转让?",
            actions:[
                { name: '售卖' },
                { name: '出租' },
                { name:'出租/售卖'},
            ]
        });
    },
    onchangeArea(e)
    {
        const x=this.selectComponent('#set-area');
        var myreg =  /^(([1-9]{1})+\d{0,6})$/;
        var y=e.detail;
        if(myreg.test(y)&&y.length!=0)
        {
            x.setData({
                error:false,
                errorMessage:''
            })
        }else{
            x.setData({
                error:true
            })
        }
    },
    onchangeLocation(e)
    {
        const x=this.selectComponent('#set-location');
    
        if(x.value!='')
        {
            x.setData({
                error:false,
                errorMessagr:''
            })
        }
    },
    onchangeAddress(e)
    {
        const x=this.selectComponent('#set-address');
        const reg =  /[\u4e00-\u9fa5]/ig; 
        var y = e.detail.replace(reg, '');
        var c=e.detail;
        if(y.length==0&&c.length!=0)
        {
            x.setData({
                error:false,
                errorMessage:''
            })
        }
        else{
            x.setData({
                error:true
            })
        }
    
    },
    onchangeDetail()
    {
        const x=this.selectComponent('#set-detail');
    
        if(x.value!='')
        {
            x.setData({
                error:false,
                errorMessage:''
            })
        }else{
            x.setData({
                error:true
            })
        }
    },
    onchangeToname()
    {
        const x=this.selectComponent('#set-toolname');
    
        if(x.value!='')
        {
            x.setData({
                error:false,
                errorMessage:''
            })
        }else{
            x.setData({
                error:true
            })
        }
    },
    onError(){
        if(this.data.selshow)
        {
            this.setData({
                selected:'元/天',
                selshow:false
            })
        }  
      },
    onchangeToaddress()
    { const x=this.selectComponent('#set-tooladdress');
    
    if(x.value!='')
    {
        x.setData({
            error:false,
            errorMessage:''
        })
    }else{
        x.setData({
            error:true
        })
    }},
    onchangeTodetail()
    {
        const x=this.selectComponent('#set-tooldetail');
        if(x.value!='')
        {
            x.setData({
                error:false,
                errorMessage:''
            })
        }else{
            x.setData({
                error:true
            })
        }
    },
    tabSelect:function(e){
        var current = e.currentTarget.dataset.id
        this.setData({
        current:current,
        fileList:''
        })
    }, 
    selshow(e)
    {
        console.log(e);
        this.setData({
            selshow:!this.data.selshow
        })
        if(this.data.selshow)
        {
            this.setData({
                selicon:'arrow-up'
            })
        }
        else{
            this.setData({
                selicon:'arrow-down'
            })
        }
    },
    selprice(e){
    this.setData({
        selshow:false,
        selected:e.target.dataset.name,
        selicon:'arrow-down'
    })
    },
    onPullDownRefresh:function () {
        setTimeout(()=>{ wx.stopPullDownRefresh({
        success: (res) => {}})},1000)  
    },
})